<?php
declare(strict_types=1);
namespace Service\ActivityService;
use App\Model\BbcModel\ActivityGoods;
use Service\BaseService;
use App\Model\BbcModel\Activity;
use App\Model\BbcModel\CouponUser;
use App\Model\BbcModel\Coupon;
use Service\UserService\MnUserService;
use App\Model\BbcModel\Mnuser;
use Service\Code\Normal;
use App\Model\BbcModel\MnActivity;
use App\Model\BbcModel\ActivityStore;
use App\Model\BbcModel\StoreActivity;
use App\Model\BbcModel\Goods;
use Service\GoodsService\MnGoodsService;

/**
 * 活动服务中心
 * @author chenshubo
 */
class ActivityService extends BaseService
{
    //  规则类型
    const act_rule_type_send        = 1;
    const act_rule_type_drop        = 2;
    const act_rule_type_discount    = 3;

    //类型
    const act_type_all_order    = 1;
    const act_type_goods_sale   = 2;
    const act_type_skill        = 3;
    const act_type_booking      = 4;

    public $status=[
        0=>'待开始',
        1=>'进行中',
        2=>'已结束'
    ];
    public $type=[
        1=>'整单促销',
        2=>'商品促销'
    ];
    public $rule_type=[
        1=>'买赠',
        2=>'直降',
        3=>'打折'
    ];
    public $target_type=[
        1=>'全场',
        2=>'会员',
        3=>'黑卡会员',
        4=>'新用户'
    ];
    public $sync_online=[
        0=>'线上及门店通用',
        1=>'线上商城',
        2=>'线下门店'
    ];
    public $unit=[
        0=>'元',
        1=>'件'
    ];
    /**
     * 下架活动数据
     */
    public function updateActivityStatusDown()
    {
        $time = time();
        Activity::instance()->where('status',0)->where('begindate','<=',$time)->update(['status'=>1]);
        Activity::instance()->where('status',1)->where('enddate','<',$time)->update(['status'=>2]);
        //优惠券状态变更
        Coupon::instance()->where('status',1)->where('begindate','<=',$time)->where('is_expiration',2)->update(['status'=>2]);
        Coupon::instance()->where('status',2)->where('enddate','<',$time)->where('is_expiration',2)->update(['status'=>3]);
        CouponUser::instance()->where('expire_time','>',0)->where('expire_time','<',$time)->where('status',1)->update(['status'=>3]);
    }
    
    
    /**
     * 活动列表
     * @param int $cid
     * @param int $mn_sid
     * @param array $body
     * @return mixed
     */
    public function getActivity(int $cid,int $mn_sid,array $body = [])
    {
        $page   = $body['page']??1;
        $limit  = $body['limit']??10;
        $time   = time();
        
        $this->updateActivityStatusDown();
        
        //获取收银机活动数据
        $table = Activity::instance()->getTable();
        $query = Activity::instance()
        ->from("{$table} as act")
        ->join('ly_activity_store as act_s','act_s.activity_id','=','act.id')
        ->where('act_s.cid',$cid)
        ->whereIn('act_s.mn_sid',[0,$mn_sid])
        ->where('act.enddate','>=',$time)
        ->whereIn('act.sync_online',[0,2])
        ->whereIn('act.type',[1,2]);
        
        $mn_user = MnUserService::getMnUserInfoByMnSid($mn_sid);
        if( $mn_user['type'] == Mnuser::TYPE_STORE_QZ ) {
            $query->whereIn('act.rule_type',[2,3]);
        }
        
        $query->whereNotExists(function($query) use ($mn_sid)
        {
            $query
            ->from('ly_store_activity as lsa')
            ->whereRaw('lsa.activity_id = act.id')
            ->where('lsa.mn_sid',$mn_sid);
        });
        
        $pageInfo = $query->paginate($limit,['act.*'], 'page', $page,true)->toArray();
        $list = $pageInfo['data'];
        
        
        $actIDs                 = array_column($list,'id');        
        $activity_discount      = ActivityDiscountService::instance()->getActDataList($actIDs);
        $activity_discount_map  = getArrayGroupData($activity_discount,'activity_id');
        $activity_drop          = ActivityDropService::instance()->getActDataList($actIDs);
        $activity_drop_map      = getArrayGroupData($activity_drop,'activity_id');
        $activity_goods         = ActivityGoodsService::instance()->getActDataList($actIDs);
        $activity_goods_map     = getArrayGroupData($activity_goods,'activity_id');
        $activity_send          = ActivitySendService::instance()->getActDataList($actIDs);
        $activity_send_map      = getArrayGroupData($activity_send,'activity_id');
        
        foreach ($list as $key => & $value)
        {
            $act_id = $value['id'];
            $value['activity_discount'] = $activity_discount_map[$act_id]??[];
            $value['activity_drop']     = $activity_drop_map[$act_id]??[];
            $value['activity_goods']    = $activity_goods_map[$act_id]??[];
            $value['activity_send']     = $activity_send_map[$act_id]??[];
        }
        return Normal::returnCode(Normal::SUC, '成功', [
            'list'          => $list,
            'totalcount'    => $pageInfo['total']
        ]);
    }
    
    /**
     * 特价活动列表
     * @param int $cid
     * @param int $mn_sid
     * @param array $body
     * @return mixed
     */
    public function getActivitySpecial(int $cid,int $mn_sid,array $body = [])
    {
        $page   = $body['page']??1;
        $limit  = $body['limit']??10;
        $time   = time();
        $pageInfo  = MnActivity::instance()
        ->where('enddate','>=',$time)
        ->where('mn_sid',$mn_sid)
        ->where('type',2)
        ->paginate($limit,['*'], 'page', $page,true)
        ->toArray();
        
        $list = $pageInfo['data'];
        $actIDs = array_column($list,'id');
        
        $mnActGoodsList = ActivityStoreService::instance()->getActivityGoodsList($actIDs);
        $mnActGoodsListMap = getArrayGroupData($mnActGoodsList,'mn_activity_id');
        foreach ($list as $key => & $value) 
        {
            $value['activity_goods']= $mnActGoodsListMap[$value['id']]??[];
        }
        return Normal::returnCode(Normal::SUC, '成功', [
            'list'          => $list,
            'totalcount'    => $pageInfo['total']
        ]);
    }

    /**
     * 获取活动是否正常和适用于场景
     * @param int $cid
     * @param int $mn_sid
     * @param $mn_user
     * @param array $activity_ids
     * @param array $goods_ids
     * @return mixed
     */
    public function getActivityIdsLink(int $cid,int $mn_sid,array $mn_user,array $activity_ids,array $goods_ids = [])
    {
        //获取店铺禁用的活动
        $disable_activity_ids = StoreActivity::instance()
            ->where(['mn_sid'=>$mn_sid])
            ->pluck('activity_id')->toArray();

        $activityList = Activity::instance()
            ->where('cid',$cid)
            ->whereIn('id',$activity_ids)
            ->whereNotIn('id',$disable_activity_ids)
            ->whereIn('status', [0, 1])
            ->get()
            ->toArray();
        if( empty($activityList) ) {
            return [];
        }

        $activityListMap = array_column($activityList,null,'id');
        $activityStore = ActivityStore::instance()
            ->where(function($query) use ($activityList,$cid,$mn_sid)
            {
                foreach ($activityList as $item)
                {
                    $activity_id = $item['id'];
                    $query->whereOr(function($query) use ($activity_id,$cid,$mn_sid)
                    {

                        $query->whereOr(function($query) use ($activity_id,$cid,$mn_sid)
                        {
                            $query
                                ->where('activity_id',$activity_id)
                                ->where('cid',$cid)
                                ->where('mn_sid',$mn_sid);
                        })
                            ->whereOr(function($query) use ($activity_id,$cid,$mn_sid)
                            {
                                $query
                                    ->where('activity_id',$activity_id)
                                    ->where('cid',$cid)
                                    ->where('mn_sid',0);
                            });
                    });
                }
            })
            ->get()
            ->toArray();
        if( empty($activityStore) ) {
            return [];
        }
        $activity_store_ids = array_column($activityStore,'activity_id');
        $mn_user_type = $mn_user['type'];
        if ( $mn_user_type == 1) { //线上分销

            $mn_goods_status = Goods::instance()
                ->select(['ly_activity_goods.activity_id','ag.goods_id'])
                ->join('ly_activity_goods', 'ly_activity_goods.goods_id=ly_goods.id')
                ->whereIn('ly_activity_goods.activity_id',$activity_store_ids)
                ->where('ly_goods.status',1)
                ->where('ly_goods.df',0)
                ->where('ly_goods.is_trade',0)
                ->where('ly_activity_goods.df',0)
                ->groupBy('ly_activity_goods.activity_id','ly_activity_goods.goods_id')
                ->get();

        } else {
            //实体店
            $mn_goods_status = ActivityGoods::instance()
                ->select(['ly_activity_goods.activity_id','ly_activity_goods.goods_id'])
                ->leftJoin('ly_mn_store_goods', 'ly_mn_store_goods.goods_id','=','ag.goods_id')
                ->where('ly_mn_store_goods.mn_sid',$mn_sid)
                ->where('ly_mn_store_goods.status',1)
                ->where('ly_mn_store_goods.df',0)
                ->whereIn('ag.activity_id',$activity_store_ids)
                ->groupBy('ag.activity_id','ag.goods_id')
                ->get();
        }
        if( empty($mn_goods_status) ) {
            return [];
        }

        //查询店铺活动商品
        if( !empty($goods_ids) )
        {
            $mn_goods_list = MnGoodsService::instance()->queryMnGoodsList($mn_sid, $goods_ids);
            if( empty($mn_goods_list) ) {
                return [];
            }
//            $mg = array_column($mn_goods_status,'activity_id','goods_id');
            $store_goods_ids = array_column($mn_goods_list,'goods_id');
            $new = [];
            foreach ($mn_goods_status as $v){
                $goods_id = $v['goods_id'];
                $activity_id = $v['activity_id'];
                if(in_array($goods_id,$store_goods_ids)){ //店铺商品参加了活动
                    $new[] = [
                        'goods_id' => $goods_id,
                        'activity_id' => $activity_id,
                        'target_type' => $activityListMap[$activity_id]['target_type'],
                        'object_status'=> 1,
                    ];
                }else{
                    $new[] = [
                        'goods_id' => $goods_id,
                        'activity_id' => $activity_id,
                        'target_type' => $activityListMap[$activity_id]['target_type'],
                        'object_status'=> 0,
                    ];
                }

            }
            return $new;
        }

        $new = [];
        foreach ($activityList as $activity_info )
        {
            if ( $activity_info['status'] == 2 ) { //已结束
                $new[] = [
                    'activity_id'   => $activity_info['id'],
                    'target_type'   => 1,
                    'object_status' => 0
                ];
            } else if(in_array($activity_info['id'],$activity_store_ids)){
                $new[] = [
                    'activity_id'   => $activity_info['id'],
                    'target_type'   => $activity_info['target_type'],
                    'object_status' => 1
                ];
            }else{
                $new[] = [
                    'activity_id'   => 0,
                    'target_type'   => $activity_info['target_type'],
                    'object_status' => 0
                ];
            }
        }
        return $new;
    }
}